package com.rock.platform.util;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import org.hibernate.JDBCException;
import org.hibernate.Session;
import org.hibernate.exception.Nestable;

public class JpaDialectUtils {
	
	@SuppressWarnings("deprecation")
	public static Connection getConnection(EntityManager em) {
		Session session = (Session) em.getDelegate();

		return session.connection();
	}

	public static String getSQLException(PersistenceException ex) {
		return getException(ex);
	}

	public static String getSQLException(Exception ex) {
		return getException(ex);
	}

	public static String getException(Throwable ex) {
		Throwable cause = getCause(ex);
		if ((cause == null) || (cause == ex)) {
			if (ex.getMessage() != null) {
				return ex.getMessage();
			}

			return ex.toString();
		}

		return getException(cause);
	}

	public static Throwable getCause(Throwable throwable) {
		if (throwable instanceof JDBCException) {
			return ((JDBCException) throwable).getSQLException();
		}

		if (throwable instanceof SQLException) {
			return ((SQLException) throwable).getNextException();
		}

		if (throwable instanceof InvocationTargetException) {
			return ((InvocationTargetException) throwable).getTargetException();
		}

		if (throwable instanceof Nestable) {
			return ((Nestable) throwable).getCause();
		}

		return throwable.getCause();
	}
}
